from playwright.sync_api import sync_playwright
from service.sjxz import sjxz_pz, sjxz_kmzd, sjxz_xmyeb, sjxz_wldw, sjxz_bmzd, sjxz_kmyeb, sjxz_xmzd
from service.rpa import rpa_login
from utils import get_cookies, create_windows
from config import ini_op
from time import strftime
import calendar

def get_date_ranges(kjnd: str, kjqj: str):
    months = sorted([int(m) for m in kjqj.split(',')])
    ranges = []

    start = months[0]
    end = start

    for i in range(1, len(months)):
        if months[i] == months[i - 1] + 1:
            end = months[i]
        else:
            ranges.append((start, end))
            start = end = months[i]
    ranges.append((start, end))  # 最后一个区间

    result = []
    for start_month, end_month in ranges:
        start_date = f"{kjnd}{start_month:02d}01"
        last_day = calendar.monthrange(int(kjnd), end_month)[1]
        end_date = f"{kjnd}{end_month:02d}{last_day:02d}"
        result.append((start_date, end_date))

    return result

def run(mode):
  timenow = str(strftime("%Y%m%d%H%M%S"))
  chrome_port = ini_op.getinivalue('app_config', 'chrome_port')[0]
  zbbh, dwbh, dwid, zbid, kmtx_id, zj = ini_op.getinivalue('basic_config', 'zbbh', 'dwbh', 'dwid', 'ledger', 'kmtx_id', 'zj')
  with sync_playwright() as playwright:
    llq = rpa_login.login(playwright, chrome_port)
    browser, context, page = llq

    # 全局请求参数cookie
    cookies = page.context.cookies()
    # 获取请求头
    cookie_list, kt, lj, jw, key1, value1, key2, value2 = ini_op.getinivalue('header_cookie', 'cookies', 'kt', 'lj', 'jw', 'key1', 'value1', 'key2', 'value2')
    header_cookie = get_cookies.getCookies(cookies, cookie_list, kt, lj, jw, key1, value1, key2, value2)

    #凭证
    if mode == 'pzsc':
      kjnd, kjqj, folderpath = ini_op.getinivalue('pz_config', 'kjnd', 'kjqj', 'folderpath')
      date_ranges = get_date_ranges(kjnd, kjqj)
      for start, end in date_ranges:
          print(f"{start} - {end}")
          sjxz_pz.run(llq, zbbh, start, end, folderpath)
      # try:
      #   if int(ksrq) - int(jsrq) > 0:
      #     create_windows.message('提示', '开始日期大于结束日期，请检查！')
      # except Exception:
      #   create_windows.message('提示', '凭证日期格式错误，请检查！')
      # if ksrq[:4] == jsrq[:4]:
      #   sjxz_pz.run(llq, zbbh, ksrq, jsrq, folderpath)
      # else:
      #   for i in range(int(jsrq[:4]) - int(ksrq[:4]) + 1):
      #     if i == 0:
      #       sjxz_pz.run(llq, zbbh, ksrq, ksrq[:4]+'1231', folderpath)
      #     elif i == int(jsrq[:4]) - int(ksrq[:4]):
      #       sjxz_pz.run(llq, zbbh, jsrq[:4]+'0101', jsrq, folderpath)
      #     else:
      #       sjxz_pz.run(llq, zbbh, str(int(ksrq[:4])+i)+'0101', str(int(ksrq[:4])+i)+'1231', folderpath)

    #项目字典
    elif mode == 'xmzdsc':
      xmlb, nd, folderpath = ini_op.getinivalue('xmzd_config', 'xmlb', 'nd', 'folderpath')
      xmlbs = xmlb.split(',')
      for xmlb in xmlbs:
        sjxz_xmzd.run(llq, dwbh, xmlb, nd, folderpath)

    #科目字典
    elif mode == 'kmzdsc':
      sjxz_kmzd.run(llq, zbbh)

    #部门字典
    elif mode == 'bmzd':
      sjxz_bmzd.run(llq, header_cookie, dwid)

    # #往来单位
    elif mode == 'wldw':
      sjxz_wldw.run(header_cookie)
    
    # #科目余额表
    elif mode == 'kmyebsc':
      sjxz_kmyeb.run(llq, zj, dwbh, zbbh)
    
    #项目余额表
    elif mode == 'xmyebsc':
      sjxz_xmyeb.run(llq, zj, dwbh, zbbh)


    
    browser.close()
    try:
      page.wait_for_selector('#cahsjjd', timeout=3000000)
    except Exception:
      pass
    finally:
      browser.close()
  
# run()